<?php
/**
 * Application level Controller
 *
 * This file is application-wide controller file. You can put all
 * application-wide controller-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Controller
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */

App::uses('Controller', 'Controller');

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @package       app.Controller
 * @link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller
{
    # Set the various components and helpers to use.
    public $helpers = array(
        'Js', 'Html', 'Form', 'Session', 'Select', 'Message'
    );

    public $components = array(
        'RequestHandler', 'Session','Cookie',
        'Auth' => array(
            'loginAction' => array('controller' => 'Users', 'action' => 'login'),
            'loginRedirect' => array('controller' => 'Dashboard', 'action' => 'index'),
            'logoutRedirect' => array('controller' => 'Users', 'action' => 'login')
        ),
        'ExcelPHP','Sms'
    );

    # User Types
    var $user_types = array(
        'admin'=>'Admin',
        'accountant'=>'Accountant',
        'store'=>'Store',
        'warehouse'=>'Warehouse',
        'service_adviser'=>'Service Adviser',
        'workshop'=>'Workshop'
    );

    # User Levels
    var $user_level = array(
        'Normal'=>'Normal',
        'Manager'=>'Manager',
        'Administrator'=>'Administrator'
    );

    # User Levels
    var $customer_types = array(
        'customer'=>'Customer',
        'service_customer'=>'Service Customer'
    );

    # Reminder
    var $reminded_status = array(
        'Reminded'=>'Reminded',
        'Not Reminded'=>'Not Reminded'
    );

    # Service Status
    var $serviced_status = array(
        'Serviced'=>'Serviced',
        'Not Serviced'=>'Not Serviced'
    );

    # Vehicle Types
    var $vehicle_types = array(
        'Bus'=>'Bus',
        'Truck'=>'Truck',
        'Earth Moving Equipment'=>'Earth Moving Equipment'
    );

    # SMS Statuses
    var $sms_status = array(
        'Delivered'=>'Delivered',
        'Failed'=>'Failed'
    );

    # Callender Repeat Frequencies
    var $cal_repeat_freq = array(
        '1-d'=>'1 Day',
        '2-d'=>'2 Days',
        '3-d'=>'3 Days',
        '4-d'=>'4 Days',
        '5-d'=>'5 Days',
        '6-d'=>'6 Days',
        '7-d'=>'1 Week',
        '14-d'=>'2 Weeks',
        '21-d'=>'3 Weeks',
        '28-d'=>'4 Weeks'
    );

    public $global_company = array();


    function beforeFilter($param_array = null)
    {
        //Renew session,
        //$this->Session->renew();
        //$this->Auth->allow('display');
        //Lets Kill Malicious codes
        /*if(isset($_POST)){
            $_POST = $this->sanitize($_POST);
        }
        if(isset($_GET)){
            $_GET  = $this->sanitize($_GET);
        }*/

        $this->Auth->allow('cronTask');

        $this->processUserCookie();
        $this->updateUserLoginTime();

        $authUser = $user_auth = $this->Auth->user();
        if($authUser['user_type'] == 'service_adviser'){
            $k = $this->_get_today_reminders_count('service_customer');
            $reminder_count = $k['count'];
            $reminder_data = $k['data'];
        }
        $this->getMessageCount();
        $auth_user_view = array(
            'permission'=>$user_auth['permission'],
            'user_type'=>$authUser['user_type']
        );
        $this->set(compact('authUser','auth_user_view','reminder_count','reminder_data'));
    }


    function cleanInput($input) {
        $search = array(
            '@<script[^>]*?>.*?</script>@si',   // Strip out javascript
            '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
            '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
            '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments
        );
        $output = preg_replace($search, '', $input);
        return $output;
    }

    function sanitize($input) {
        //debug($input);
        if (is_array($input)) {
            $output = array();
            foreach($input as $var=>$val) {
                $output[$var] = $this->sanitize($val);
            }
        }
        else {
            if (get_magic_quotes_gpc()) {
                $input = stripslashes($input);
            }
            $input  = $this->cleanInput($input);
            $new_enough_php = function_exists("mysql_real_escape_string");//i.e. PHP >= v4.3.0
            if($new_enough_php)
            {//PHP v4.3.0 or higher
                //undo any magic quote effects so mysql_real_escape_string can do the work
                // $output = mysql_real_escape_string($input);
            }
            $output = $input;
        }
        return $output;
    }

    function updateUserLoginTime()
    {
        $authUser = $this->Auth->user();
        if($authUser){
            $User = ClassRegistry::init('User');
            $User->updateAll(
                $this->sanitize(array('User.login_update_time' => "'".date('Y-m-d H:i:s')."'")),
                $this->sanitize(array('User.id' => $authUser['id']))
            );
        }
    }

    function processUserCookie()
    {
        if($this->Auth->user()){}
        else{//If the session has expired, then read from the cookie and clear the login session and time from the db
            $user_id = $this->Cookie->read('c_user_id');
            if($user_id != null){
                $User = ClassRegistry::init('User');
                $User->updateAll(
                    //array('User.login_session' => "''",'User.login_update_time' => "''"),
                    $this->sanitize(array('User.login_session' => "''")),
                    $this->sanitize(array('User.id' => $user_id))
                );
                $this->Cookie->delete('c_user_id');
            }
        }
    }


    function getHolidays(){
        # Holiday Dates
        $sms_status = array(
            '01-01'=>'New Year',
            '03-06'=>'Independence Day',
            '05-01'=>'Labour Day',
            '05-25'=>'African Day',
            '07-01'=>'Republic Day',
            '09-21'=>'Christmas Day',
            '12-26'=>'Boxing Day'
        );
        //Farmers day is fisr friday of every year
        $timestamp = strtotime('first fri of last month');
        $farmers_day = date('m-d',strtotime($timestamp));
        //debug(date('Y-12-Friday'));
        debug($farmers_day);
    }


    protected  function convertToExcel($list_headers,$param ,$filename)
    {
        $company_profile = $this->global_company;
        $objPHPExcel = new PHPExcel();

        // Set document properties
        $objPHPExcel->getProperties()->setCreator("WARP-D_".$company_profile['name'])
            ->setLastModifiedBy("WARP-D_".$company_profile['name'])
            ->setTitle("Office 2007 XLSX WARP-D ".$company_profile['name']." Document")
            ->setSubject("Office 2007 XLSX WARP-D ".$company_profile['name']." Document")
            ->setDescription($company_profile['name']." document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory($company_profile['name']." result file");

        // Set default font
        $objPHPExcel->getDefaultStyle()->getFont()->setName('Arial')->setSize(10);

        $count_h = 1;
        foreach($list_headers as $header){
            $letter_h = $this->getAlphabetCharacter($count_h);
            $objPHPExcel->getActiveSheet()->setCellValue($letter_h.'1', $header);
            $count_h++;
        }
        //Bold the headers
        $letter_h = $this->getAlphabetCharacter($count_h -1);
        $objPHPExcel->getActiveSheet()->getStyle('A1:'.$letter_h.'1')->getFont()->setBold(true);

        $it = 2;
        foreach ($param as $item) {
            $count_inner = 1;
            foreach($item as $itm){
                $letter_h = $this->getAlphabetCharacter($count_inner);
                $objPHPExcel->getActiveSheet()->setCellValue($letter_h.$it, strip_tags($itm));
                $count_inner++;
            }
            $it++;
        }

        // Rename worksheet
        $objPHPExcel->getActiveSheet()->setTitle('Page_1');

        $objPHPExcel->setActiveSheetIndex(0);

        return array(
            'excel_obj' => $objPHPExcel,
            'filename' => $filename
        );
    }

    function getAlphabetCharacter($index)
    {
        $alphabet = array(1=>'A',2=>'B',3=>'C',4=>'D',5=>'E',6=>'F',7=>'G',8=>'H',9=>'I',10=>'J',11=>'K',12=>'L',13=>'M',14=>'N',15=>'O',16=>'P'
        ,17=>'Q',18=>'R',19=>'S',20=>'T',21=>'U',22=>'V',23=>'W',24=>'X',25=>'Y',26=>'Z');
        return $alphabet[$index];
    }

    function randomString($length)
    {
        $original_string = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'),array(time()),array('_','!','?','=','-','[',']','+','$','#','^','&'));
        $original_string = implode("", $original_string);
        return substr(str_shuffle($original_string), 0, $length);
    }

    function convertDate($date = null, $type = 'mysql')
    {
        $res = '';
        if ($type == 'mysql') {
            $res = date("Y-m-d", strtotime($date));
        }
        elseif ($type == 'mysql_flip') {
            $res = date("d-m-Y", strtotime($date));
        }
        elseif ($type == 'ui') {
            $res = date("F d, Y", strtotime($date));
        }
        elseif($type == 'formal'){
            $res = date("m/d/Y", strtotime($date));
        }
        return $res;
    }

    function getMonths($index = null)
    {
        $months = array('01'=>'January','02'=>'February','03'=>'March','04'=>'April','05'=>'May','06'=>'June','07'=>'July','08'=>'August','09'=>'September','10'=>'October','11'=>'November','12'=>'December');
        if($index){
            return $months[$index];
        }
        else{
            return $months;
        }
    }

    function getTanksProductTypes($index = null)
    {
        $pro = array('AGO'=>'AGO','PMS'=>'PMS','Kerosene'=>'Kerosene','Premix'=>'Premix','MGO'=>'MGO','LPG'=>'LPG','RFO'=>'RFO');
        if($index){
            return $pro[$index];
        }
        else{
            return $pro;
        }
    }


    function count_time_between_dates($smaller_date, $bigger_date,$count_type='months')
    {
        $d1 = strtotime($smaller_date); //Smaller
        $d2 = strtotime($bigger_date); //Bigger
        $min_date = min($d1, $d2);
        $max_date = max($d1, $d2);
        $i = 0;
        $type = "+1 month";
        if($count_type == 'hours'){
            $type = "+1 hours";
        }
        elseif($count_type == 'days'){
            $type = "+1 day";
        }
        elseif($count_type == 'weeks'){
            $type = "+1 week";
        }
        elseif($count_type == 'years'){
            $type = "+1 year";
        }
        while (($min_date = strtotime($type, $min_date)) <= $max_date) {
            $i++;
        }
        return $i;
    }


    function formatNumber($value = 0, $type = 'number', $decimal_place = 2)
    {
        if ($type == 'money') {
            $num = number_format($value, $decimal_place, '.', ',');
        } else {
            $num = number_format($value, $decimal_place, '.', '');
        }

        return $num;
    }


    function __add_ordinal_suffix($num)
    {
        $last = substr($num, -1);
        if (strlen($num) < 2) {
            $next_to_last = 0;
        } else {
            $next_to_last = substr($num, -2);
        }
        if ($next_to_last >= 10 && $next_to_last < 20) {
            $suff = "th";
        } else
            if ($last == 1) {
                $suff = "st";
            } else
                if ($last == 2) {
                    $suff = "nd";
                } else
                    if ($last == 3) {
                        $suff = "rd";
                    } else {
                        $suff = "th";
                    }

        return number_format($num) . $suff;
    }

    function getMessageCount()
    {
        $authUser = $this->Auth->user();
        $MessageReciever = ClassRegistry::init('MessageReciever');
        $user_inbox = $MessageReciever->find('count',array(
            'conditions'=>array('MessageReciever.user_id'=>$authUser['id'], 'MessageReciever.msg_status'=>'unread','MessageReciever.trash'=>'n'),
            'recursive'=>-1
        ));
        $this->set(compact('user_inbox'));
        return $user_inbox;
    }


    function _get_today_reminders_count($type = 'service_customer',$filter_reminded = true){
        $ModelObj = ClassRegistry::init('CustomerAppointment');
        return $ModelObj->today_reminders_count($type,$filter_reminded);
    }


    function _get_today_appointments_count($type = 'service_customer',$filter_serviced = true){
        $ModelObj = ClassRegistry::init('CustomerAppointment');
        return $ModelObj->today_appointments_count($type,$filter_serviced);
    }

    function _get_overdue_appointments($type='reminders',$customer_type = 'service_customer'){
        $ModelObj = ClassRegistry::init('CustomerAppointment');
        return $ModelObj->overdue_appointments($type,$customer_type);
    }


    function getWeekDates()
    {
        $today = date('Y-m-d');
        //w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday)
        $dates_arr = array();
        $day_of_week = intval(date("w"));
        $dates_arr[$day_of_week] = $today;
        $start = $day_of_week - 1;
        $reduce = 1;
        for ($x = $start; $x >= 0; $x--) {
            $today = date('Y-m-d', strtotime("-$reduce day"));
            $dates_arr[$x] = $today;
            $reduce++;
        }
        return $dates_arr;
    }


    function send_message($params,$plist=null){
        $loggedUser = $this->Auth->user();
        $user_id = $loggedUser['id'];

        # disable the rendering of the layout
        $this->autoRender = false;
        $this->autoLayout = false;

        $User = ClassRegistry::init('User');
        $Message = ClassRegistry::init('Message');
        $list = array();
        //Build the Message receivers if any
        if(isset($params['Message']['to'])){
            $tos = $params['Message']['to'];
            $usernames = explode(',',$tos);
            $find_list = array();
            foreach($usernames as $usr){
                $find_list[] = trim($usr);
            }
            $find_list = array_unique($find_list);
            $list = $User->find('list', array(
                'fields'=>array('User.id'),
                'conditions' => array('User.username' => $find_list),
                'recursive' => -1
            ));
        }
        elseif($plist){
            $list = $plist;
        }

        if(!$list){
            return array('code' => 1, 'mesg' => __('Reciepient(s) Not Found'));
        }

        $receivers = array('MessageReciever'=>array());
        foreach($list as $user){
            $receivers['MessageReciever'][] = array(
                'user_id'=>$user
            );
        }
        $params['MessageReciever'] = $receivers['MessageReciever'];

        $save = $Message->saveAll($this->sanitize($params));

        # save the data
        if ($save) {
            //Save to address book
            return array('code' => 0, 'mesg' => __('Message Sent'));
        }
        else {
            return array('code' => 1, 'mesg' => __('Message Not Sent'));
        }
    }


    function getMessageAddressList($bdc_id,$omc_id,$bdc_user_type=array(),$omc_user_type=array(),$exclude=array(), $type='bdc')
    {
        $OmcUser = ClassRegistry::init('OmcUser');
        $BdcUser = ClassRegistry::init('BdcUser');

        $conditions_omc = array('OmcUser.omc_id' => $omc_id,'OmcUser.omc_user_type'=>$omc_user_type);
        if($type == 'omc'){
            $conditions_omc['NOT']=array('OmcUser.user_id' => $exclude);
        }
        $all_omc_users = $OmcUser->find('list', array(
            'fields'=>array('OmcUser.user_id'),
            'conditions' => $conditions_omc,
            'recursive' => -1
        ));

        $conditions_bdc =array('BdcUser.bdc_id' => $bdc_id,'BdcUser.bdc_user_type'=>$bdc_user_type);
        if($type == 'bdc'){
            $conditions_bdc['NOT']=array('BdcUser.user_id' => $exclude);
        }
        $all_bdc_users = $BdcUser->find('list', array(
            'fields'=>array('BdcUser.user_id'),
            'conditions' => $conditions_bdc,
            'recursive' => -1
        ));

        $all_users = array_merge($all_omc_users,$all_bdc_users);

        return $all_users;
    }


    function get_region_district(){
        $company_profile = $this->global_company;
        $regions = $this->Region->find('all', array(
            'fields' => array('Region.id', 'Region.name'),
            'conditions' => array('Region.deleted' => 'n'),
            'contain'=>array('District'=>array('fields' => array('District.id', 'District.name'))),
            'recursive' => 1
        ));
        $glbl_region_district = array();
        $regions_lists = array();
        $district_lists = array();
        foreach ($regions as $value) {
            $regions_lists[] = $value['Region'];
            foreach ($value['District'] as $val) {
                $district_lists[] = $val;
                $glbl_region_district[$value['Region']['id']][$val['id']] = $val['name'];
            }
        }

        return array(
            'region'=>$regions_lists,
            'district'=>$district_lists,
            'region_district'=>$glbl_region_district,
        );
    }
}
